var enterKey = 13;

function escapeHTML(input) {

	var result = "";

	for ( var i = 0; i < input.length; i++) {
		if (input.charAt(i) == "&" && input.length - i - 1 >= 4 && input.substr(i, 4) != "&amp;") {
			result = result + "&amp;";
		} else if (input.charAt(i) == "<") {
			result = result + "&lt;";
		} else if (input.charAt(i) == ">") {
			result = result + "&gt;";
		} else {
			result = result + input.charAt(i);
		}
	}

	return result;
};

/* Add a function to the date type to let us parse ISO-formatted dates */

Date.prototype.setISO = function(string) {

	var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" + "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" + "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
	var d = string.match(new RegExp(regexp));

	var offset = 0;
	var date = new Date(d[1], 0, 1);

	if (d[3]) {
		date.setMonth(d[3] - 1);
	}
	if (d[5]) {
		date.setDate(d[5]);
	}
	if (d[7]) {
		date.setHours(d[7]);
	}
	if (d[8]) {
		date.setMinutes(d[8]);
	}
	if (d[10]) {
		date.setSeconds(d[10]);
	}
	if (d[12]) {
		date.setMilliseconds(Number("0." + d[12]) * 1000);
	}
	if (d[14]) {
		offset = (Number(d[16]) * 60) + Number(d[17]);
		offset *= ((d[15] == '-') ? 1 : -1);
	}

	offset -= date.getTimezoneOffset();
	time = (Number(date) + (offset * 60 * 1000));
	this.setTime(Number(time));
};

function serialiseXml(data) {

	var xml = new XMLSerializer(data).serializeToString(data.documentElement);

	var formatted = '';
	var reg = /(>)(<)(\/*)/g;
	xml = xml.replace(reg, '$1\r\n$2$3');
	var pad = 0;
	jQuery.each(xml.split('\r\n'), function(index, node) {
		var indent = 0;
		if (node.match(/.+<\/\w[^>]*>$/)) {
			indent = 0;
		} else if (node.match(/^<\/\w/)) {
			if (pad != 0) {
				pad -= 1;
			}
		} else if (node.match(/^<\w[^>]*[^\/]>.*$/)) {
			indent = 1;
		} else {
			indent = 0;
		}

		var padding = '';
		for ( var i = 0; i < pad; i++) {
			padding += '    ';
		}

		formatted += padding + node + '\r\n';
		pad += indent;
	});

	return formatted;

}

